package com.tc.itfarm.commons.mybatis.plugins;


import static org.mybatis.generator.internal.util.StringUtility.stringHasValue;
import static org.mybatis.generator.internal.util.messages.Messages.getString;

import java.io.File;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
import org.mybatis.generator.api.dom.java.Interface;
import org.mybatis.generator.api.dom.java.Method;
import org.mybatis.generator.api.dom.java.TopLevelClass;
import org.mybatis.generator.exception.ShellException;
import org.mybatis.generator.internal.DefaultShellCallback;
/**
 * 
 * @Description: copy的 能用就行 不需要了解
 * @author: wangdongdong  
 * @date:   2016年7月4日 下午2:53:08   
 *
 */
public class RenameJavaClientPlugin extends PluginAdapter {
    private String searchString;
    private String replaceString;
    private Pattern pattern;

    /**
     *
     */
    public RenameJavaClientPlugin() {
    }


    public boolean validate(List<String> warnings) {

        searchString = properties.getProperty("searchString"); //$NON-NLS-1$
        replaceString = properties.getProperty("replaceString"); //$NON-NLS-1$

        boolean valid = stringHasValue(searchString) && stringHasValue(replaceString);

        if (valid) {
            pattern = Pattern.compile(searchString);
        } else {
            if (!stringHasValue(searchString)) {
                warnings.add(getString("ValidationError.18", //$NON-NLS-1$
                        "RenameJavaClientPlugin", //$NON-NLS-1$
                        "searchString")); //$NON-NLS-1$
            }
            if (!stringHasValue(replaceString)) {
                warnings.add(getString("ValidationError.18", //$NON-NLS-1$
                        "RenameJavaClientPlugin", //$NON-NLS-1$
                        "replaceString")); //$NON-NLS-1$
            }
        }
        return valid;
    }

    @Override
    public boolean clientGenerated(Interface interfaze, TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {

        boolean success = false;
        String targetProject = properties.getProperty("targetProject");
        String targetPackage = properties.getProperty("targetPackage");
        String modelTargetPackage = properties.getProperty("modelTargetPackage");
        DefaultShellCallback defaultShellCallback = new DefaultShellCallback(false);
        File targetFile;
        try {
            File directory = defaultShellCallback.getDirectory(targetProject, targetPackage);
            targetFile = new File(directory, String.format("%sDao.java", introspectedTable.getTableConfiguration().getDomainObjectName()));
            if (targetFile.exists()) {
                return false;
            }
        } catch (ShellException e) {
            return false;
        }

        String daoInterfaceType = String.format(properties.getProperty("daoInterfacePackage") + ".SingleTableDao<%s, %s>",
                String.format(modelTargetPackage + ".%s", introspectedTable.getTableConfiguration().getDomainObjectName()),
                String.format(modelTargetPackage + ".%sCriteria", introspectedTable.getTableConfiguration().getDomainObjectName()));
        FullyQualifiedJavaType fullyQualifiedJavaType = new FullyQualifiedJavaType(daoInterfaceType);
        interfaze.addSuperInterface(fullyQualifiedJavaType);
        interfaze.addImportedType(fullyQualifiedJavaType);
        interfaze.addImportedType(new FullyQualifiedJavaType(String.format(modelTargetPackage + ".%s", introspectedTable.getTableConfiguration().getDomainObjectName())));
        interfaze.addImportedType(new FullyQualifiedJavaType(String.format(modelTargetPackage + ".%sCriteria", introspectedTable.getTableConfiguration().getDomainObjectName())));
        success = super.clientGenerated(interfaze, topLevelClass, introspectedTable);
        Iterator<Method> methodIterator = interfaze.getMethods().iterator();
        while (methodIterator.hasNext()) {
            Method method = methodIterator.next();
            if (method.getName().equals("countByCriteria") || method.getName().equals("deleteByCriteria")
                    || method.getName().equals("deleteById") || method.getName().equals("insert")
                    || method.getName().equals("insertSelective") || method.getName().equals("selectByCriteria")
                    || method.getName().equals("selectById") || method.getName().equals("updateByCriteriaSelective")
                    || method.getName().equals("updateByCriteria") || method.getName().equals("updateByIdSelective")
                    || method.getName().equals("updateById")) {
                methodIterator.remove();
            }
        }
        return success;
    }

    @Override
    public void initialized(IntrospectedTable introspectedTable) {

        String oldType = introspectedTable.getMyBatis3JavaMapperType();

        introspectedTable.setCountByExampleStatementId("countByCriteria"); //$NON-NLS-1$
        introspectedTable.setDeleteByExampleStatementId("deleteByCriteria"); //$NON-NLS-1$
        introspectedTable.setDeleteByPrimaryKeyStatementId("deleteById"); //$NON-NLS-1$
        introspectedTable.setInsertStatementId("insert"); //$NON-NLS-1$
        introspectedTable.setInsertSelectiveStatementId("insertSelective"); //$NON-NLS-1$
//        introspectedTable.setSelectAllStatementId("selectAll"); //$NON-NLS-1$
        introspectedTable.setSelectByExampleStatementId("selectByCriteria"); //$NON-NLS-1$
        introspectedTable.setSelectByExampleWithBLOBsStatementId("selectByCriteriaWithBLOBs"); //$NON-NLS-1$
        introspectedTable.setSelectByPrimaryKeyStatementId("selectById"); //$NON-NLS-1$
        introspectedTable.setUpdateByExampleStatementId("updateByCriteria"); //$NON-NLS-1$
        introspectedTable.setUpdateByExampleSelectiveStatementId("updateByCriteriaSelective"); //$NON-NLS-1$
        introspectedTable.setUpdateByExampleWithBLOBsStatementId("updateByCriteriaWithBLOBs"); //$NON-NLS-1$
        introspectedTable.setUpdateByPrimaryKeyStatementId("updateById"); //$NON-NLS-1$
        introspectedTable.setUpdateByPrimaryKeySelectiveStatementId("updateByIdSelective"); //$NON-NLS-1$
        introspectedTable.setUpdateByPrimaryKeyWithBLOBsStatementId("updateByIdWithBLOBs"); //$NON-NLS-1$
        introspectedTable.setBaseResultMapId("BaseResultMap"); //$NON-NLS-1$
        introspectedTable.setResultMapWithBLOBsId("ResultMapWithBLOBs"); //$NON-NLS-1$
        introspectedTable.setExampleWhereClauseId("Criteria_Where_Clause"); //$NON-NLS-1$
        introspectedTable.setBaseColumnListId("Base_Column_List"); //$NON-NLS-1$
        introspectedTable.setBlobColumnListId("Blob_Column_List"); //$NON-NLS-1$
        introspectedTable.setMyBatis3UpdateByExampleWhereClauseId("Update_By_Criteria_Where_Clause"); //$NON-NLS-1$

        Matcher matcher = pattern.matcher(oldType);
        oldType = matcher.replaceAll(replaceString);

        introspectedTable.setMyBatis3JavaMapperType(oldType);
    }
}
